import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

/**
 * 表格数据加载和分页的钩子函数
 * @param {Function} fetchData - 获取数据的函数
 * @param {Object} options - 配置选项
 * @param {Object} options.defaultParams - 默认查询参数
 * @param {Boolean} options.immediate - 是否立即加载数据
 * @param {Number} options.defaultPageSize - 默认每页显示条数
 * @returns {Object} 表格数据和方法
 */
export function useTable(fetchData, options = {}) {
  const {
    defaultParams = {},
    immediate = true,
    defaultPageSize = 10
  } = options

  // 表格数据
  const tableData = ref([])
  
  // 加载状态
  const loading = ref(false)
  
  // 分页信息
  const pagination = reactive({
    currentPage: 1,
    pageSize: defaultPageSize,
    total: 0,
    pageSizes: [10, 20, 50, 100]
  })
  
  // 查询参数
  const queryParams = reactive({ ...defaultParams })
  
  // 排序信息
  const sortInfo = reactive({
    prop: '',
    order: ''
  })
  
  // 加载数据
  const loadData = async (params = {}) => {
    try {
      loading.value = true
      
      // 构建请求参数
      const requestParams = {
        ...queryParams,
        page: pagination.currentPage,
        size: pagination.pageSize,
        ...params
      }
      
      // 添加排序参数
      if (sortInfo.prop) {
        requestParams.sortBy = sortInfo.prop
        requestParams.sortOrder = sortInfo.order === 'ascending' ? 'asc' : 'desc'
      }
      
      const response = await fetchData(requestParams)
      
      // 处理响应数据
      if (response && response.data) {
        tableData.value = response.data.records || response.data || []
        pagination.total = response.data.total || response.data.length || 0
      } else {
        tableData.value = []
        pagination.total = 0
      }
    } catch (error) {
      console.error('加载数据失败', error)
      ElMessage.error(error.message || '加载数据失败')
      tableData.value = []
      pagination.total = 0
    } finally {
      loading.value = false
    }
  }
  
  // 刷新数据
  const refresh = () => {
    pagination.currentPage = 1
    loadData()
  }
  
  // 重置查询
  const reset = () => {
    Object.assign(queryParams, defaultParams)
    pagination.currentPage = 1
    pagination.pageSize = defaultPageSize
    Object.assign(sortInfo, { prop: '', order: '' })
    loadData()
  }
  
  // 处理页码变化
  const handleCurrentChange = (page) => {
    pagination.currentPage = page
    loadData()
  }
  
  // 处理每页显示条数变化
  const handleSizeChange = (size) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    loadData()
  }
  
  // 处理排序变化
  const handleSortChange = (sort) => {
    if (sort.prop) {
      sortInfo.prop = sort.prop
      sortInfo.order = sort.order
    } else {
      Object.assign(sortInfo, { prop: '', order: '' })
    }
    loadData()
  }
  
  // 更新查询参数
  const updateQueryParams = (params) => {
    Object.assign(queryParams, params)
    pagination.currentPage = 1
    loadData()
  }
  
  // 获取当前查询参数
  const getCurrentQueryParams = () => {
    return {
      ...queryParams,
      page: pagination.currentPage,
      size: pagination.pageSize
    }
  }
  
  // 设置分页信息
  const setPagination = (pageInfo) => {
    if (pageInfo.currentPage) {
      pagination.currentPage = pageInfo.currentPage
    }
    if (pageInfo.pageSize) {
      pagination.pageSize = pageInfo.pageSize
    }
    if (pageInfo.total !== undefined) {
      pagination.total = pageInfo.total
    }
  }
  
  // 设置排序信息
  const setSortInfo = (sort) => {
    Object.assign(sortInfo, sort)
  }
  
  // 组件挂载时是否立即加载数据
  onMounted(() => {
    if (immediate) {
      loadData()
    }
  })
  
  return {
    tableData,
    loading,
    pagination,
    queryParams,
    sortInfo,
    loadData,
    refresh,
    reset,
    handleCurrentChange,
    handleSizeChange,
    handleSortChange,
    updateQueryParams,
    getCurrentQueryParams,
    setPagination,
    setSortInfo
  }
}